package com.huilian.iotbox.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.huilian.iotbox.admin.service.QiNiuService;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.enums.BaiduImageStatusEnum;
import com.huilian.iotbox.data.exception.SysException;
import com.huilian.iotbox.data.properties.ImageProperties;
import com.huilian.iotbox.data.properties.QiniuProperties;
import com.huilian.iotbox.data.service.BaiduApiService;
import com.huilian.iotbox.data.service.ErrorLogCommonService;
import com.huilian.iotbox.data.utils.DateTimeUtils;
import com.huilian.iotbox.data.utils.Util;
import com.jcraft.jsch.ChannelSftp;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Region;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Slf4j
@Service
public class QiNiuServiceImpl implements QiNiuService {

    @Autowired
    private BaiduApiService baiduApiService;

    @Autowired
    private QiniuProperties qiniuProperties;
    @Autowired
    private ImageProperties imageProperties;
    @Autowired
    private ErrorLogCommonService errorLogCommonService;

    /**
     * 1 身份证正面 2 身份证反面 3 营业执照图片 4 组织机构代码证图片 5 开户许可证照片
     * 6  门头照    9 场地内景照 8 收银台照    11 手持身份证照      12 租赁合同    7 其他图片 13 银行卡正面
     */
    @Override
    public JSONObject imgVad(String imgName, String imgUrl, Integer type) throws IOException {
        if (type == 1 || type == 2) {
            try {
                JSONObject json = baiduApiService.getIdentityPeriod(imgName, imgUrl, type);
                if (type == 1 && !BaiduImageStatusEnum.NORMAL.getCode().equals(json.get("imageStatus"))) {
                    throw new SysException(json.getString("msg"));
                }
                if (type == 2 && !BaiduImageStatusEnum.NORMAL.getCode().equals(json.get("imageStatus"))) {
                    throw new SysException(json.getString("msg"));
                }
                return json;
            } catch (SysException e) {
                throw new SysException(e.getMessage());
            }
        }
        if (type == 3) {
            try {
                JSONObject jsonBuss = baiduApiService.getBusiness(imgName, imgUrl);
                String staData = (String) jsonBuss.get("staData");
                if (StringUtils.isBlank(staData) || "无".equals(staData)) {
                    throw new SysException("请上传清晰营业执照");
                }
                return jsonBuss;
            } catch (Exception e) {
                throw new SysException("请上传清晰营业执照");
            }
        }
        if (type == 13) {
            JSONObject jsonBuss = baiduApiService.getBankCard(imgName, imgUrl);
            String bankCardNumber = (String) jsonBuss.get("bankCardNumber");
            if (StringUtils.isBlank(bankCardNumber) || "无".equals(bankCardNumber)) {
                throw new SysException("请上传清晰结算银行卡正面");
            }
            return jsonBuss;
        }
        return null;
    }

    @Override
    public ServerResponse uploadImage(MultipartFile multipartFile, Integer type) {
        String newName = UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";
        try {
            JSONObject result = new JSONObject();
//            String oldName = multipartFile.getOriginalFilename();
            //1.2使用IDUtils工具类生成新的文件名，新文件名 = newName + 文件后缀
//            newName = newName + oldName.substring(oldName.lastIndexOf("."));
            //1.3生成文件在服务器端存储的子目录
            String filePath = DateTimeUtils.getCurrentShortDateStr();
            InputStream input = multipartFile.getInputStream();
            ChannelSftp sftp = Util.ftpLogin(imageProperties.getHost(), imageProperties.getPort(), imageProperties.getUserName(),
                    imageProperties.getPassWord(), imageProperties.getBasePath());

            sftp.put(input, newName);
            if (type != null) {
                if (type == 1 || type == 2 || type == 3 || type == 13) {
                    String tempUrl = imageProperties.getBaseUrl() + newName;
                    result = this.imgVad(newName, tempUrl, type);
                }
            }
            result.put("keyRes", newName);
            return ServerResponse.createBySuccess(result);
        } catch (Exception e) {
            errorLogCommonService.writerInfoException("uploadImage-删除图片失败", newName, e);
            return ServerResponse.createByErrorMessage("图片上传失败");
        }
    }

    /**
     * 调用这个接口要先去后缀，例如"10e9646ba1164ddabe0e2b456203c6b2.jpg"去掉传入"10e9646ba1164ddabe0e2b456203c6b2"
     * @param fileName
     * @return
     */
    @Override
    public ServerResponse deleteByFileNameToFTP(String fileName) {
        fileName = fileName + ".jpg";
        try {
            ChannelSftp sftp = Util.ftpLogin(imageProperties.getHost(), imageProperties.getPort(), imageProperties.getUserName(),
                    imageProperties.getPassWord(), imageProperties.getBasePath());

            if (sftp == null) {
                return ServerResponse.createByErrorMessage("ftp登录失败");
            }
            sftp.rm(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            errorLogCommonService.writerInfoException("deleteByFileNameToFTP-删除图片失败", fileName, e);
            return ServerResponse.createByErrorMessage("删除文件失败");
        }
        return ServerResponse.createBySuccess();
    }

    @Override
    public ServerResponse deleteQiNiuImage(String key) {
        Configuration cfg = new Configuration(Region.region2());
        Auth auth = Auth.create(qiniuProperties.getAccessKey(), qiniuProperties.getSecretKey());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(qiniuProperties.getBucket(), key);
            return ServerResponse.createBySuccess("图片删除成功");
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
            errorLogCommonService.writerInfoException("deleteQiNiuImage-删除图片失败", key, ex);
            return ServerResponse.createByErrorMessage("图片删除失败");
        }
    }

    /**
     * 上传图片到七牛
     */
    @Override
    public ServerResponse fileupload(MultipartFile multipartFile, Integer type) {
        JSONObject result = new JSONObject();
        try {
            //zong1() 代表华南地区
            Configuration cfg = new Configuration(Region.region2());
            UploadManager uploadManager = new UploadManager(cfg);
            Auth auth = Auth.create(qiniuProperties.getAccessKey(), qiniuProperties.getSecretKey());

            String qiniuBucket = qiniuProperties.getBucket();
            String upToken = auth.uploadToken(qiniuBucket);
//            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");//设置日期格式
//            String dateStr = df.format(new Date());
//            String originalFilename = multipartFile.getOriginalFilename();
//            String key_res = dateStr + originalFilename.substring(originalFilename.lastIndexOf("."));
            //为了图片安全性推荐使用UUID
            String keyRes = UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";
//            String key_res = dateStr;  // 去掉.jpg
            Response response = uploadManager.put(multipartFile.getBytes(), keyRes, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

            log.info("图片上传成功: {}", keyRes);
            if (type != null) {
                if (type == 1 || type == 2 || type == 3 || type == 13) {
                    try {
                        String tempUrl = qiniuProperties.getImgUrl() + keyRes;
//                        result = this.imgVad(keyRes, tempUrl, type);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return ServerResponse.createByErrorMessage(e.getMessage());
                    }
                }
            }
            result.put("keyRes", keyRes);

            return ServerResponse.createBySuccess(result);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            return ServerResponse.createByErrorMessage("图片上传失败");
        } catch (IOException e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("图片上传失败");
        }
    }

}
